package com.xm.xmapp;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.alibaba.fastjson.JSON;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips.InputtipsListener;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.xm.xmapp.adapter.PoiItemAdapter;
import com.xm.xmapp.adapter.SuggestionCityAdapter;
import com.xm.xmapp.app.CodeConstant;
import com.xm.xmapp.app.MyAppcation;
import com.xm.xmapp.base.BaseActivity;
import com.xm.xmapp.exception.MyException;
import com.xm.xmapp.myinterface.ListViewOnclickInterFace;
import com.xm.xmapp.response.bean.ResponseSearchHistory;
import com.xm.xmapp.tools.MyCache;
import com.xm.xmapp.tools.Tools;

@SuppressLint("ClickableViewAccessibility")
public class PoiKeywordSearchActivity extends BaseActivity implements InputtipsListener, OnPoiSearchListener,
		OnClickListener, GeocodeSearch.OnGeocodeSearchListener {

	private EditText keyWord;// 要输入的poi搜索关键字
	private TextView quxiao;
	private Button clear_search_history_btn;

	private PoiResult poiResult; // poi返回的结果
	private int currentPage = 0;// 当前页面，从0开始计数
	private PoiSearch.Query query;// Poi查询条件类
	private PoiSearch poiSearch;// POI搜索
	private ArrayList<ResponseSearchHistory> list;
	private ArrayList<SuggestionCity> list1;
	private String suggustCity = "";

	private ListView xListView;
	private PoiItemAdapter adapter;
	private SuggestionCityAdapter adapter1;
	private TextView tishi;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_poikeywordsearch);
	}

	@Override
	public void initView() {

		xListView = (ListView) findViewById(R.id.xListView);
		keyWord = (EditText) findViewById(R.id.keyword);
		quxiao = (TextView) findViewById(R.id.quxiao);
		tishi = (TextView) findViewById(R.id.tishi);
		clear_search_history_btn = (Button) findViewById(R.id.clear_search_history_btn);
	}

	@Override
	public void initData() {

		intent = getIntent();
		suggustCity = "郑州市";
		if (MyAppcation.getMyAppcation().getMyLocation() != null) {
			GeocodeSearch geocoderSearch = new GeocodeSearch(this);
			geocoderSearch.setOnGeocodeSearchListener(this);//和上面一样
// 第一个参数表示一个Latlng(经纬度)，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
			LatLonPoint latLonPoint = new LatLonPoint(MyAppcation.getMyAppcation().getLocation().getLatitude(),MyAppcation.getMyAppcation().getLocation().getLongitude());
			RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,GeocodeSearch.AMAP);
			geocoderSearch.getFromLocationAsyn(query);
		}


		list = new ArrayList<ResponseSearchHistory>();
		list1 = new ArrayList<SuggestionCity>();
		adapter = new PoiItemAdapter(list, this, R.layout.item_poikeysearch);
		xListView.setAdapter(adapter);
		adapter.setIn(new ListViewOnclickInterFace() {

			@Override
			public Object DoSomeThing(Object data) {

				ResponseSearchHistory t = (ResponseSearchHistory) data;
				intent.putExtra("bean", t);
				setResult(CodeConstant.AddressCode, intent);
				finish();
				try {
					ArrayList<ResponseSearchHistory> list = new ArrayList<ResponseSearchHistory>();
					String searchCity = MyCache.getMyCache().getCache(CodeConstant.SearchCity);
					if (searchCity != null && !searchCity.equals("")) {
						int tenpi = -1;
						list.addAll(JSON.parseArray(searchCity, ResponseSearchHistory.class));
						for (int i = 0, size = list.size(); i < size; i++) {

							if (list.get(i).title.equals(t.title)) {
								tenpi = i;
								break;
							}

						}
						if (tenpi != -1) {
							list.remove(tenpi);
						}
						list.add(0, t);
						if (list.size() > 10)
							list.remove(10);
					} else {
						list.add(t);
					}

					if (list.size() != 0) {
						MyCache.getMyCache().putCache(CodeConstant.SearchCity, JSON.toJSONString(list));
					}
				} catch (Exception e) {
					MyException.printStackTrace(e);
				}

				return null;
			}
		});

		adapter1 = new SuggestionCityAdapter(list1, this, R.layout.item_listactivity);
		adapter1.setIn(new ListViewOnclickInterFace() {

			@Override
			public Object DoSomeThing(Object data) {
				currentPage = 0;
				suggustCity = ((SuggestionCity) data).getCityName();
				query = new PoiSearch.Query(keyWord.getText().toString(), "", suggustCity);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
				query.setPageSize(20);// 设置每页最多返回多少条poiitem
				query.setPageNum(currentPage);// 设置查第一页

				poiSearch = new PoiSearch(PoiKeywordSearchActivity.this, query);
				poiSearch.setOnPoiSearchListener(PoiKeywordSearchActivity.this);
				poiSearch.searchPOIAsyn();

				return null;
			}
		});

		String searchCity = MyCache.getMyCache().getCache(CodeConstant.SearchCity);
		if (searchCity != null && !searchCity.equals(""))
			list.addAll(JSON.parseArray(searchCity, ResponseSearchHistory.class));

		clear_search_history_btn.setVisibility(View.GONE);
		tishi.setVisibility(View.GONE);
		if (list.size() > 0) {
			clear_search_history_btn.setVisibility(View.VISIBLE);
			tishi.setVisibility(View.VISIBLE);
			adapter.notifyDataSetChanged();
		}

	}

	@Override
	public void initEvent() {

		quxiao.setOnClickListener(this);
		clear_search_history_btn.setOnClickListener(this);
		keyWord.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// et.getCompoundDrawables()得到一个长度为4的数组，分别表示左右上下四张图片
				Drawable drawable = keyWord.getCompoundDrawables()[2];
				// 如果右边没有图片，不再处理
				if (drawable == null)
					return false;
				// 如果不是按下事件，不再处理
				if (event.getAction() != MotionEvent.ACTION_UP)
					return false;
				if (event.getX() > keyWord.getWidth() - keyWord.getPaddingRight() - drawable.getIntrinsicWidth()) {
					keyWord.setText("");
				}
				return false;
			}
		});
		keyWord.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					currentPage = 0;
					query = new PoiSearch.Query(keyWord.getText().toString(), "", suggustCity);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
					query.setPageSize(20);// 设置每页最多返回多少条poiitem
					query.setPageNum(currentPage);// 设置查第一页

					poiSearch = new PoiSearch(PoiKeywordSearchActivity.this, query);
					poiSearch.setOnPoiSearchListener(PoiKeywordSearchActivity.this);
					poiSearch.searchPOIAsyn();
					promptDialog.show();
				}

				return false;
			}
		});

		keyWord.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

				currentPage = 0;
				query = new PoiSearch.Query(keyWord.getText().toString(), "", suggustCity);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
				query.setPageSize(20);// 设置每页最多返回多少条poiitem
				query.setPageNum(currentPage);// 设置查第一页

				poiSearch = new PoiSearch(PoiKeywordSearchActivity.this, query);
				poiSearch.setOnPoiSearchListener(PoiKeywordSearchActivity.this);
				poiSearch.searchPOIAsyn();
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		});
	}

	@Override
	public void onGetInputtips(List<Tip> arg0, int arg1) {

	}

	@Override
	public void onPoiItemSearched(PoiItem arg0, int arg1) {

	}

	@Override
	public void onPoiSearched(PoiResult result, int rCode) {

		promptDialog.dismiss();
		if (rCode == 1000) {
			if (result != null && result.getQuery() != null) {// 搜索poi的结果
				if (result.getQuery().equals(query)) {// 是否是同一条
					poiResult = result;
					// 取得搜索到的poiitems有多少页
					List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
					List<SuggestionCity> suggestionCities = poiResult.getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息

					if (poiItems != null && poiItems.size() > 0) {
						list.clear();
						clear_search_history_btn.setVisibility(View.GONE);
						tishi.setVisibility(View.GONE);
						ArrayList<ResponseSearchHistory> temp = (ArrayList<ResponseSearchHistory>) JSON.parseArray(
								JSON.toJSONString(poiItems), ResponseSearchHistory.class);
						list.addAll(temp);

						xListView.setAdapter(adapter);
						adapter.notifyDataSetChanged();

					} else if (suggestionCities != null && suggestionCities.size() > 0) {
						clear_search_history_btn.setVisibility(View.GONE);
						tishi.setVisibility(View.GONE);
						// suggustCity = suggestionCities.get(0).getCityName();
						list1.clear();
						list1.addAll(suggestionCities);
						// xListView.setAdapter(adapter1);
						// adapter1.notifyDataSetChanged();
						Tools.showMessage("暂无地址信息");

					} else {
						// ToastUtil.show(PoiKeywordSearchActivity.this,
						// R.string.no_result);
						Tools.showMessage("暂无地址信息");
					}
				}
			} else {
				// ToastUtil.show(PoiKeywordSearchActivity.this,
				// R.string.no_result);
			}
		} else {
			// ToastUtil.showerror(this, rCode);
		}
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.quxiao:
			finish();

			break;

		case R.id.clear_search_history_btn:

			MyCache.getMyCache().reMoveCache(CodeConstant.SearchCity);
			// MyAppcation.getMyAppcation().clearData();
			list.clear();
			adapter.notifyDataSetChanged();
			tishi.setVisibility(View.GONE);
			clear_search_history_btn.setVisibility(View.GONE);
			break;

		default:
			break;
		}
	}

	@Override
	public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
		if (rCode == 1000) {
			if (result != null && result.getRegeocodeAddress() != null
					&& result.getRegeocodeAddress().getFormatAddress() != null) {
				suggustCity = result.getRegeocodeAddress().getCity();
			} else {
				suggustCity = "郑州市";
			}
		}
	}

	@Override
	public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

	}
}
